from django.shortcuts import render

# 导入modelviewset视图模型
from libs.custom_model_view_set import CustomModelViewSet

# 导入模型
from .models import User, Token, Permissions, Roles

# 导入序列化
from .serializers import UserSerializer, PermissionsSerializer, RolesSerializer

# 导入过滤、搜索和排序插件
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend

# 导入生成token
import uuid
# 导入自定义加密模块
from libs.md5 import md5

# 导入自定义返回值
from rest_framework.response import Response


class UserViewSet(CustomModelViewSet):
    queryset = User.objects.all()      # 导入模型类所有数据
    serializer_class = UserSerializer   # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('username',)  # 指定可过滤的字段
    search_fields = ('name',)  # 指定可搜索的字段

    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "name"]

    def create(self, request, *args, **kwargs):
        # 获取前端提交字段
        username = request.data.get('username')
        password = request.data.get('password')

        # 判断提交数据是否空
        if not username:
            return Response({"code": "400", "msg": "账号为空"})

        elif not password:
            return Response({"code": "400", "msg": "密码为空"})

        # 判断账号是否存在
        is_exists = User.objects.filter(username=username).exists()
        if is_exists:
            return Response({"code": "500", "msg": "账号已存在"})


        # 对密码加密重写赋值
        password = md5(password)
        self.request.data['password'] = password

        # 重写序列化数据
        serializer = self.get_serializer(data=request.data)

        # 效验数据是否正确
        serializer.is_valid(raise_exception=True)

        # 进行数据创建
        self.perform_create(serializer)

        # 一对一
        user_obj = User.objects.get(username=username)
        token = str(uuid.uuid4())
        Token.objects.create(User=user_obj, token_key=token)

        res = {'code': 200, 'msg': '用户创建成功'}
        return Response(res)

    def update(self, request, *args, **kwargs):
        username = request.data.get('username')
        roleId = int(request.data.get('role'))

        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        # 一对多
        User.objects.filter(username=username).update(role_id=roleId)   # 更新一对多字段
        res = {'code': 200, 'msg': '更新成功'}
        return Response(res)


class PermissionsViewSet(CustomModelViewSet):
    queryset = Permissions.objects.all()      # 导入模型类所有数据
    serializer_class = PermissionsSerializer   # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('name',)  # 指定可过滤的字段
    search_fields = ('name',)  # 指定可搜索的字段

    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "name"]

class RolesViewSet(CustomModelViewSet):
    queryset = Roles.objects.all()      # 导入模型类所有数据
    serializer_class = RolesSerializer   # 序列化数据

    # 导入模块，filters.SearchFilter 是指搜索, filters.OrderingFilter 是指排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)

    filterset_fields = ('role',)  # 指定可过滤的字段
    search_fields = ('role',)  # 指定可搜索的字段

    # 排序
    # 注意 filter_backends多了一个filters.OrderingFilter
    ordering_fields = ["id", "role"]

    def update(self, request, *args, **kwargs):
        print(request.data)

        # 获取前端提交数据
        roles = request.data.get('role')
        permissions_list = request.data.get('permissions')


        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        # 添加多对多字段
        Roles_obj = Roles.objects.get(role=roles)
        Roles_obj.permissions.clear()   #先清空关联表中的相关数据，再遍历列表重新添加
        # 遍历权限所有字段id, 在进行添加
        for permissions_list_dict in permissions_list:
            print(permissions_list_dict['id'])
            permissions_list_id = Permissions.objects.get(id=permissions_list_dict['id'])  # 根据id查询分组
            Roles_obj.permissions.add(permissions_list_id)

        res = {'code': 200, 'msg': '更新成功'}
        return Response(res)

    def destroy(self, request, *args, **kwargs):
        print(request.data)
        instance = self.get_object()
        try:
            roles = Roles.objects.get(role=instance)
            roles.permissions.clear()
            self.perform_destroy(instance)
            res = {'code': 200, 'msg': '删除成功'}
        except Exception as e:
            res = {'code': 500, 'msg': '其他用户关联了角色，请删除关联的角色再操作'}
        return Response(res)